import { useState, useEffect } from 'react';
import io from 'socket.io-client';

let socket;
export default function Home() {
  const [isConnect, setIsConnect] = useState(false);
  const [messages, setMessages] = useState([
    {
      user: "Admin alan223",
      msg: "Welcome!",
    },
  ]);
  const [inputMessage, setInputMessage] = useState("");

  useEffect(() => {
    socket = io('http://localhost:4000');
    socket.on('connect', () => {
      console.log('Connected to the socket.io server!');
      setIsConnect(true);
    });
    socket.on('message', (msg) => {
      setMessages((prevMessages) => {
        return [
          ...prevMessages,
          JSON.parse(msg),
        ];
      });
    });

    return () => {
      socket.disconnect();
    };
  }, []);

  const handleSendMessage = (e) => {
    if (e.key === "Enter" && inputMessage.trim()) {
      socket.emit("message", inputMessage);

      // Append to the messages
      setMessages((prevMessages) => {
        return [
          ...prevMessages,
          {
            user: "Me",
            msg: inputMessage,
          },
        ];
      });

      setInputMessage("");
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-700 via-gray-900 to-black text-white flex flex-col">
      <div
        className={`text-xs text-center py-2 ${
          isConnect ? 'bg-green-500' : 'bg-yellow-500'
        } transition-colors duration-300`}
      >
        {isConnect ? 'Connected' : 'Connecting...'}
      </div>

      <h1 className="text-center text-4xl font-extrabold py-8 text-indigo-400 animate-pulse">
        Simple Chatroom
      </h1>

      <div className="flex-1 p-4 overflow-y-auto">
        <ul className="space-y-3">
          {messages.map((message, index) => (
            <li
              key={index}
              className={`flex items-start ${
                message.user === "Me" ? 'justify-end' : 'justify-start'
              }`}
            >
              <div
                className={`max-w-xs px-4 py-2 rounded-lg shadow-md text-sm ${
                  message.user === "Me"
                    ? 'bg-indigo-500 text-white self-end'
                    : 'bg-gray-800 text-gray-200'
                }`}
              >
                <span className="font-bold mr-2">{message.user}:</span>
                {message.msg}
              </div>
            </li>
          ))}
        </ul>
      </div>

      <div className="p-4">
        <input
          value={inputMessage}
          onChange={(e) => setInputMessage(e.target.value)}
          onKeyDown={handleSendMessage}
          type="text"
          placeholder="Type a message..."
          className="w-full bg-gray-800 text-white text-lg px-4 py-2 rounded-lg shadow focus:outline-none focus:ring-2 focus:ring-indigo-400"
        />
      </div>
    </div>
  );
}
